package com.ambimmort.shj.service.dpi.users.group.adsl;

import cn.net.greenet.common.db_service.BaseDao;
import cn.net.greenet.common.policy_service.PolicySupport;
import cn.net.greenet.db.HibernateUtil;
import cn.net.greenet.db.bean.Dpiusergroup;
import cn.net.greenet.db.bean.UgUsername;
import com.ambimmort.umessage.UcType;
import com.ambimmort.umessage.uc.outgoing.vm.x40;
import com.ambimmort.umessage.util.HexUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.PrintWriter;
import java.sql.ResultSet;
import java.util.ArrayList;

/**
 * Created by Administrator on 2015/7/30.
 */
@Service("adslCreateService")
public class CreateService {

    @Autowired
    private SessionFactory hibernateSessionFactory;
    ResultSet rs =null;
    BaseDao baseDao = null;

    private void init() {
        baseDao = new BaseDao();
    }

    private void close() {
        if (baseDao != null) {
            baseDao.close();
        }
    }
    /**
     *
     * @param json
     * @throws Throwable
     */
    public void adslCreate(String json) throws Throwable{
        JSONObject jsonObj = JSONObject.fromObject(json);
        String groupId = jsonObj.getString("groupId");
        JSONArray usernames = jsonObj.getJSONArray("usernames");

        init();
        String sql="select * from dpiusergroup where id="+groupId;
        Object[] params ={};
        rs=baseDao.executeSQL(sql,params);
        try {
            while(!rs.next()){
                String sq="insert into ug_username(DPIUserGroup_id,name)values(?,?)";
                Object[] param ={groupId,usernames};
                baseDao.executeUpdate(sq,param);
            }

            java.util.List<x40> msgs = new ArrayList<x40>();

            x40.User user = null;
            x40 msg = null;
            for (int i = 0; i < usernames.size(); i++) {
                if ((i) % 2000 == 0) {
                    msg = new x40();
                    msg.getHeader().setMessageNo(UcType.newUINT4(0));
                    msg.getHeader().setMessageSequenceNo(UcType.newUINT4(0));
                    msg.getHeader().setMessageType(new UcType.UINT1(new byte[]{(byte)0x40}));
                    msg.setAction(UcType.newUINT1(1));
                    msg.setUserGroupName(UcType.newUString_UINT1(rs.getString("name")));
                    msg.setUserGroupNo(UcType.newUINT2(rs.getInt("DPIUserGroup_id")));
                    msg.setMessageSerialNo(UcType.newUINT4(0));
                    msgs.add(msg);
                }
                user = new x40.User();
                user.setUserName(UcType.newUString_UINT1(usernames.getString(i)));
                user.setUserType(UcType.newUINT1(1));
                msg.getUserNum().add(user);
            }
            // TODO: change the print method to PolicySupport invocation
            for (x40 m : msgs) {
                System.out.println(JSONObject.fromObject(m.toJSON()).toString(4));
                System.out.println(HexUtil.getHex(m.toBytes()));
                String comment = "【"+rs.getString("DPIUserGroup_id")+"("+rs.getString("name")+")"+"】【user】【＋】【"+usernames.size()+"】";
                System.out.println(comment);
                PolicySupport.getInstance().getApi().addPolicy("0x40", rs.getString("instanceName"), m.toJSON(), comment);
            }

//        SessionFactory sf = HibernateUtil.getSessionFactory();
//        Session session = sf.openSession();
//        Dpiusergroup bean = (Dpiusergroup) session.get(Dpiusergroup.class, Integer.parseInt(groupId));
//        Transaction tx = session.beginTransaction();
//        try {
//            for (int i = 0; i < usernames.size(); i++) {
//                UgUsername uu = new UgUsername(bean);
//                uu.setName(usernames.getString(i));
//                session.saveOrUpdate(uu);
//            }
//            tx.commit();
//
//            java.util.List<x40> msgs = new ArrayList<x40>();
//
//            x40.User user = null;
//            x40 msg = null;
//            for (int i = 0; i < usernames.size(); i++) {
//                if ((i) % 2000 == 0) {
//                    msg = new x40();
//                    msg.getHeader().setMessageNo(UcType.newUINT4(0));
//                    msg.getHeader().setMessageSequenceNo(UcType.newUINT4(0));
//                    msg.getHeader().setMessageType(new UcType.UINT1(new byte[]{(byte)0x40}));
//                    msg.setAction(UcType.newUINT1(1));
//                    msg.setUserGroupName(UcType.newUString_UINT1(bean.getName()));
//                    msg.setUserGroupNo(UcType.newUINT2(bean.getId()));
//                    msg.setMessageSerialNo(UcType.newUINT4(0));
//                    msgs.add(msg);
//                }
//                user = new x40.User();
//                user.setUserName(UcType.newUString_UINT1(usernames.getString(i)));
//                user.setUserType(UcType.newUINT1(1));
//                msg.getUserNum().add(user);
//            }


//            // TODO: change the print method to PolicySupport invocation
//            for (x40 m : msgs) {
//                System.out.println(JSONObject.fromObject(m.toJSON()).toString(4));
//                System.out.println(HexUtil.getHex(m.toBytes()));
//                String comment = "【"+bean.getId()+"("+bean.getName()+")"+"】【user】【＋】【"+usernames.size()+"】";
//                System.out.println(comment);
//                PolicySupport.getInstance().getApi().addPolicy("0x40", bean.getInstanceName(), m.toJSON(), comment);
//            }

//            return "{\"result\":\"true\"}";
        } catch (Exception e){
            e.printStackTrace();
//            out.println("{\"result\":\"false\"}");
//            tx.rollback();
        } finally {
            close();
//            out.close();
//            session.close();
        }

    }

}
